package com.kkd.kkdapp.activity;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import pl.droidsonroids.gif.GifDrawable;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.AccountInfoRes;
import com.kkd.kkdapp.http.entity.BankCard;
import com.kkd.kkdapp.http.entity.BankMessage;
import com.kkd.kkdapp.http.entity.DepositTipsData;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpClient;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.keyboard.StockKeyboardView;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.EditText.FinanceEditText;
import com.kkd.kkdapp.view.EditText.FinanceEditText.onFinanceEditListener;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 充值
 * 
 * @author mty
 * 
 * @refactor 赵闯 2016-5-17
 */
public class RechargeActivity extends BaseActivity {

	private static final int RED_NOTE = 0; // 读取短信
	private static final int ACCOUNTINFO_CODE_ZERO = 1; // 账户余额code=0
	private static final int ACCOUNTINFO_CODE_ELSE = 2; // 账户余额code=其它
	private static final int RECHARGE_SUCCESS = 3; // 充值成功
	private static final int RECHARGE_FAIL = 4; // 充值失败
	private static final int CREAT_RECHARGE_SUCCESS = 5; // 创建充值页面成功
	private static final int CREAT_RECHARGE_FAIL = 6; // 创建充值页面失败

	private RelativeLayout recharge_title_img; // 返回
	private RelativeLayout pop_line;
	// private String version; // 手机当前版本号
	private Button present_button; // 下一步
	private Button recharge_bt;// 确认充值
	private FinanceEditText centre_ed; // 输入金额
	private ImageView close;
	private List<BankMessage> mList;
	private RelativeLayout send_verify; // 获取验证码
	private StockKeyboardView mKeyboardView;
	private StockKeyboardView mKeyboardView2;
	private TextView balance_tv; // 账户余额
	private TextView cardname_tv; // 银行卡名字
	private ImageView bank_logo; // 银行卡logo
	private TextView cardno_tv; // 银行卡号
	private TextView recharge_count_tv; // 充值金额
	private TextView details;
	private ImageView progressbar;
	private TextView tip_bankname;
	private EditText recharge_verify_ed; // 输入验证码
	private String ticket = ""; // 验证信息/充值推进时使用
	private String orderId = ""; // 流水号/充值推进时使用
	private double balance; // 返回余额
	private String rechargeMax; // 单笔充值最大限额
	private TextView mastrict; // 最大限额
	private String amount; // 返回充值金额
	private String newMisTips; // 是否显示新手任务
	private String depositTips1;
	private String depositTips2;
	private String depositTips3;
	private TextView verfition_visibility;
	private TextView count_down;
	private TextView count_tv;
	private int time;
	private TimerTask mTimerTask;
	private Timer timer;
	// private boolean VERIFYFLAG = false;
	private boolean SENDVERIFYFLAG = true;
	private String patternCoder = "(?<!\\d)\\d{4,6}(?!\\d)";
	// private BroadcastReceiver smsReceiver;
	// private IntentFilter filter2;
	private String strContent;
	private String str;
	private String balances;
	private String limitinfo;
	private BankCard card;
	private RelativeLayout recharge_verify_rl;
	private String[] bankStatusas;
	private String wapDepositUrl;
	private AccountInfoRes mAccountInfo;
	private ImageView zaixian;
	private int code;
	private Dialog dialog_newtask;
	private Dialog loadDialog;
	private Dialog mDialog;
	private Dialog mSinaDialog;
	
	private String mobileTransferUrl;//手机
	private String alipayTransferUrl;//支付宝
	private String otherTransferUrl;//其他
	
	/**********DECLARES*************/
	private RelativeLayout zfb_rechange;
	private RelativeLayout phone_bank_recharge;
	private RelativeLayout other_recharge;
	/**********INITIALIZES*************/
	
	
	/* Please visit http://www.ryangmattison.com for updates */
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case ACCOUNTINFO_CODE_ZERO:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				if (mAccountInfo.getWithholdAuth().getWithdrawStatus() == 1) {

					showSinaDialog();
				}

				// 设置是否显示新手任务
				if (TextUtils.isEmpty(newMisTips)) {
					rel_new_task.setVisibility(View.GONE);
				} else {
					if (!TextUtils.isEmpty(depositTips1)
							&& !TextUtils.isEmpty(depositTips2)
							&& !TextUtils.isEmpty(depositTips3)) {
						tv_tip_black.setText(depositTips1);
						tv_tip_orange.setText(depositTips2);
						tv_tip_sum.setText(depositTips3);
						rel_new_task.setVisibility(View.VISIBLE);
						// tv_time_newTask.setText(newMisTips);
						updateNewTaskSpaceTime();
						startTime();
					} else {
						rel_new_task.setVisibility(View.GONE);
					}
				}
				balance_tv.setText(balances);
				ImageLoader.getInstance().displayImage(card.getImageUrl(),
						bank_logo);

				String bankStatus = card.getBankStatus();// String("bankStatus");
				String czExt = card.getCzExt();// String("czExt");
				if (!bankStatus.endsWith("null")) {
					bankStatusas = bankStatus.split(",");
					if (bankStatusas[0].equals("1")) {
						recharge_verify_rl.setVisibility(View.VISIBLE);
						mastrict.setText(limitinfo);
						present_button.setVisibility(View.VISIBLE);
						zaixian.setVisibility(View.GONE);
						if (mList != null)
							tip_bankname.setText(mList.get(0).getBankName()
									+ "充值限额");
					} else if (bankStatusas[0].equals("0")) {
						recharge_verify_rl.setVisibility(View.GONE);
						mastrict.setText(czExt);
						present_button.setVisibility(View.GONE);
						zaixian.setVisibility(View.VISIBLE);
						if (mList != null)
							tip_bankname.setText(mList.get(0).getBankName()
									+ "充值方式变更");
					}
				}

				break;
			case RED_NOTE: // 读取短信
				recharge_verify_ed.setText(strContent);
				break;
			case ACCOUNTINFO_CODE_ELSE:
				int statusCode = (Integer) msg.obj;
				if (statusCode == KkdHttpClient.NO_NET) {
					showToast("网络错误，请稍后重试");
				} else if (statusCode == KkdHttpClient.RESOLUTION_EXCEPTION) {
					showToast("服务异常，请稍后重试");
				}
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				break;
			case RECHARGE_SUCCESS:
				break;
			case RECHARGE_FAIL:
				String fail_reason = (String) msg.obj;
				if (fail_reason.equals("验证码错误")) {
					errorTimerCancel();
					showToast(fail_reason);
					resumeVerify();
				} else {
					progressbar.setImageResource(R.drawable.recharge_failture);
					details.setText(fail_reason);
				}
				if (code == 258) {
					showDialog("抱歉,无法完成充值,此银行卡余额不足");
				}
				break;
			case CREAT_RECHARGE_SUCCESS:
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				Intent intent = new Intent(RechargeActivity.this,
						KKDSinaWebActivity.class);
				intent.putExtra("url", "");
				System.out.println("页面内容" + msg.obj.toString());
				intent.putExtra("data", msg.obj.toString());
				intent.putExtra("useTitleName", true);
				intent.putExtra("titleName", "新浪支付");
				startActivityForResult(intent, KKDSinaWebActivity.SET_PWD);
				break;
			case CREAT_RECHARGE_FAIL:
				int statusCode1 = (Integer) msg.obj;
				if (statusCode1 == KkdHttpClient.NO_NET) {
					showToast("网络错误，请稍后重试");
				} else if (statusCode1 == KkdHttpClient.RESOLUTION_EXCEPTION) {
					showToast("服务异常，请稍后重试");
				}
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				break;
			}
		};
	};
	private View rel_new_task;
	private TextView tv_time_newTask;
	private TextView tv_tip_orange;
	private TextView tv_tip_black;
	private TextView tv_tip_sum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recharge);
		initView();
		setListener();
		// getSMSVerificationCode();
	}

	protected void showSinaDialog() {
		if (mSinaDialog != null) {
			mSinaDialog.cancel();
			mSinaDialog = null;
		}
		try {
			String text = "";

			if (mAccountInfo.getWithholdAuth().getIsSinaPayPassword() == 0) {
				text = mAccountInfo.getWithholdAuth().getPayPasswordTips();
			} else if (mAccountInfo.getWithholdAuth().getIsWithholdAuth() == 0) {
				text = mAccountInfo.getWithholdAuth().getWithholdAuthTips();
			}
			if (!TextUtils.isEmpty(text)) {
				mSinaDialog = DialogUtils.generate2BDialog(this, text, "去设置",
						"再看看", new OnClickListener() {

							@Override
							public void onClick(View v) {
								mSinaDialog.dismiss();

								Intent intent = new Intent(
										RechargeActivity.this,
										KKDSinaWebActivity.class);
								intent.putExtra("url", mAccountInfo
										.getWithholdAuth()
										.getSinaWithholdAuthUrl());
								intent.putExtra("useTitleName", true);
								intent.putExtra("titleName", "新浪支付");
								startActivityForResult(intent,
										KKDSinaWebActivity.SET_PWD);
							}
						}, new OnClickListener() {

							@Override
							public void onClick(View v) {
								mSinaDialog.dismiss();
								finish();
							}
						});
				mSinaDialog.show();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getAccountInfo();
	}

	/**
	 * 初始化界面
	 */
	public void initView() {
		// 新手任务
		rel_new_task = findViewById(R.id.rel_new_task);
		tv_time_newTask = (TextView) findViewById(R.id.tv_time_newTask);
		tv_tip_orange = (TextView) findViewById(R.id.tv_tip_orange);
		tv_tip_black = (TextView) findViewById(R.id.tv_tip_black);
		tv_tip_sum = (TextView) findViewById(R.id.tv_tip_sum);
		//三种充值方式
		zfb_rechange = (RelativeLayout) findViewById(R.id.zfb_rechange);
		phone_bank_recharge = (RelativeLayout) findViewById(R.id.phone_bank_recharge);
		other_recharge = (RelativeLayout) findViewById(R.id.other_recharge);
		
		recharge_title_img = (RelativeLayout) this
				.findViewById(R.id.recharge_title_img);
		pop_line = (RelativeLayout) this.findViewById(R.id.pop_line);
		present_button = (Button) this.findViewById(R.id.present_button);
		centre_ed = (FinanceEditText) this.findViewById(R.id.centre_ed);
		centre_ed.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT) {
					if (present_button.isEnabled())
						rechargeNext();
				}
				return false;
			}
		});
		balance_tv = (TextView) this.findViewById(R.id.balance_tv);
		cardname_tv = (TextView) this.findViewById(R.id.cardname_tv);
		bank_logo = (ImageView) findViewById(R.id.bank_logo);
		cardno_tv = (TextView) this.findViewById(R.id.cardno_tv);
		tip_bankname = (TextView) findViewById(R.id.tip_bankname);
		send_verify = (RelativeLayout) this.findViewById(R.id.send_verify);
		mKeyboardView = (StockKeyboardView) findViewById(R.id.keyboard);
		mKeyboardView2 = (StockKeyboardView) findViewById(R.id.keyboard2);

		// DefineKeyboardUtil.getInstance().setKeyboardView(mKeyboardView2);
		// DefineKeyboardUtil.getInstance().setEditText(centre_ed);
		// DefineKeyboardUtil.getInstance().showKeyboard();
		recharge_verify_ed = (EditText) this
				.findViewById(R.id.recharge_verify_ed);
		recharge_verify_ed
				.setOnEditorActionListener(new OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE) {
							if (recharge_bt.isEnabled())
								rechargeAction();
						}
						return false;
					}
				});
		recharge_bt = (Button) findViewById(R.id.recharge_bt);
		recharge_count_tv = (TextView) findViewById(R.id.recharge_count_tv);
		details = (TextView) findViewById(R.id.details);
		progressbar = (ImageView) findViewById(R.id.progressbar);
		close = (ImageView) findViewById(R.id.close);
		mastrict = (TextView) this.findViewById(R.id.astrict_tv);
		verfition_visibility = (TextView) this
				.findViewById(R.id.verfition_visibility);
		count_down = (TextView) this.findViewById(R.id.count_down);
		count_tv = (TextView) this.findViewById(R.id.count_tv);
		recharge_verify_rl = (RelativeLayout) this
				.findViewById(R.id.recharge_verify_rl);
		zaixian = (ImageView) this.findViewById(R.id.zaixian);
		zaixian.setOnClickListener(new OnSingleClickListener() {

			@Override
			public void onSingleClick(View v) {
				if (!TextUtils.isEmpty(centre_ed.getText().toString())
						&& Double.parseDouble(centre_ed.getText().toString()) >= 2) {
					onlineBankingDialog(centre_ed.getText().toString(),
							wapDepositUrl);
				} else if (TextUtils.isEmpty(centre_ed.getText().toString())) {
					Toast.makeText(RechargeActivity.this, "请输入充值金额",
							Toast.LENGTH_SHORT).show();
				} else if (Double.parseDouble(centre_ed.getText().toString()) < 2) {
					Toast.makeText(RechargeActivity.this, "充值金额不得低于2元",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		resumeVerify();
		requestBankList();
	}

	/**
	 * 设置监听
	 */
	public void setListener() {
		zfb_rechange.setOnClickListener(mOnClick);
		phone_bank_recharge.setOnClickListener(mOnClick);
		other_recharge.setOnClickListener(mOnClick);
		recharge_title_img.setOnClickListener(mOnClick);
		present_button.setOnClickListener(mOnClick);
		recharge_bt.setOnClickListener(mOnClick);
		send_verify.setOnClickListener(mOnClick);
		close.setOnClickListener(mOnClick);
		centre_ed.setFinanceEditListener(new onFinanceEditListener() {

			@Override
			public void onValueChanged(double toValue, double fromValue) {
				// TODO Auto-generated method stub

				if (!TextUtils.isEmpty(rechargeMax)) {// 充值限额是否为空
					if ("".equals(centre_ed.getText().toString())
							|| Double.parseDouble(centre_ed.getText()
									.toString()) < 2) {
						present_button.setEnabled(false);
					} else {
						present_button.setEnabled(true);
						if (toValue > Double.parseDouble(rechargeMax)) {
							showDialog("该银行卡快捷支付单笔交易限额" + rechargeMax
									+ "，大额交易请使用网银");
							centre_ed.setText(rechargeMax);
							centre_ed.setSelection(centre_ed.getText()
									.toString().length());
						}

					}
				}

			}

			@Override
			public void onOutLimit() {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterValueChanged(double toValue) {
				// TODO Auto-generated method stub

			}
		});

		recharge_verify_ed.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (TextUtils.isEmpty(s.toString())
						|| s.toString().length() < 1) {
					recharge_bt.setEnabled(false);
				} else {
					recharge_bt.setEnabled(true);
				}
			}
		});
	}

	OnSingleClickListener mOnClick = new OnSingleClickListener() {

		@Override
		public void onSingleClick(View v) {
			switch (v.getId()) {
			case R.id.recharge_title_img: // 返回
				finish();
				break;
			case R.id.present_button: // 下一步

				rechargeNext();

				break;
			case R.id.send_verify: // 获取验证码
				disposeSendVerify();
				break;
			case R.id.recharge_bt:
				rechargeAction();
				break;
			case R.id.close:
				closePopwin();
				break;
			case R.id.zfb_rechange:
				toZfbActivity();
				break;
			case R.id.phone_bank_recharge:
				toPBank();
				break;
			case R.id.other_recharge:
				toOtherRecharge();
				break;
			}
		}

		private void toOtherRecharge() {
			Intent intent=new Intent(RechargeActivity.this,KKDWebActivity.class);
			intent.putExtra("url", otherTransferUrl);
			startActivity(intent);
		}

		private void toPBank() {
			Intent intent=new Intent(RechargeActivity.this, KKDWebActivity.class);
			intent.putExtra("url",mobileTransferUrl);
			startActivity(intent);
		}

		private void toZfbActivity() {
			Intent intent=new Intent(RechargeActivity.this, KKDWebActivity.class);
			intent.putExtra("url",alipayTransferUrl);
			startActivity(intent);
		}
	};

	public void closePopwin() {
		pop_line.setVisibility(View.GONE);
	}

	protected void rechargeNext() {

		if (mAccountInfo != null
				&& mAccountInfo.getWithholdAuth().getWithdrawStatus() == 1) {
			if (mAccountInfo.getWithholdAuth().getIsWithholdAuth() == 0) {
				showSinaDialog();
			} else {

				String count = centre_ed.getText().toString();
				if (count.endsWith("."))
					count = count.substring(0, count.length() - 1);

				createHostingDepositByOnlineBank(count);

			}

		} else {
			disposeSendVerify();
			showPopwin();
		}
	}

	private void createHostingDepositByOnlineBank(String count) {

		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "正在请求新浪充值...");

		KkdHttpMagager.getInstance().createHostingDepositByOnlineBank(count,
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {

						Message msg = new Message();
						msg.what = CREAT_RECHARGE_SUCCESS;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = CREAT_RECHARGE_FAIL;
						msg.obj = statusCode;
						mHandler.sendMessage(msg);
					}
				});
	}

	public void showPopwin() {
		SystemUtils.hideKeyBoard(RechargeActivity.this);
		recharge_verify_ed.requestFocus();
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(recharge_verify_ed, InputMethodManager.SHOW_IMPLICIT);
		String count = centre_ed.getText().toString();
		if (count.endsWith("."))
			count = count.substring(0, count.length() - 1);
		recharge_count_tv.setText(count);
		pop_line.setVisibility(View.VISIBLE);
		recharge_verify_rl.setVisibility(View.VISIBLE);
		recharge_bt.setVisibility(View.VISIBLE);
		progressbar.setVisibility(View.GONE);
		details.setVisibility(View.GONE);
		// DefineKeyboardUtil.getInstance().setKeyboardView(mKeyboardView);
		// DefineKeyboardUtil.getInstance().setEditText(recharge_verify_ed);
		// recharge_verify_ed.setOnEditorActionListener(new
		// OnEditorActionListener() {
		//
		// @Override
		// public boolean onEditorAction(TextView v, int actionId, KeyEvent
		// event) {
		// if(actionId==EditorInfo.IME_ACTION_GO){
		// rechargeAction();
		// }
		// return false;
		// }
		// });
		// DefineKeyboardUtil.getInstance().showKeyboard();
	}

	public void resumeVerify() {
		recharge_verify_rl.setVisibility(View.VISIBLE);
		recharge_bt.setVisibility(View.VISIBLE);
		progressbar.setVisibility(View.GONE);
		details.setVisibility(View.GONE);
		send_verify.setClickable(true);
	}

	public void rechargeAction() {
		SystemUtils.onEvent("Account_RechargePage_Submit", 1);
		// DefineKeyboardUtil.getInstance().hideKeyboard();
		SystemUtils.hideKeyBoard(RechargeActivity.this);
		recharge_verify_rl.setVisibility(View.GONE);
		recharge_bt.setVisibility(View.GONE);
		details.setVisibility(View.VISIBLE);
		progressbar.setVisibility(View.VISIBLE);

		if ("".equals(ticket) || "".equals(orderId)) {
			showDialog("验证码失效，请重新获取验证码！");
			resumeVerify();
			errorTimerCancel();
		} else {
			if (!str.equals(amount)) {
				showDialog("充值的金额有变动，请重新获取验证码！");
				resumeVerify();
				errorTimerCancel();
			} else {

				GifDrawable drawable;
				try {
					drawable = new GifDrawable(getResources(),
							R.drawable.loading_gif);

					progressbar.setImageDrawable(drawable);
				} catch (NotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				close.setClickable(false);
				nextRechrge();
			}

		}

	}

	/**
	 * 处理发送验证码按钮事件
	 */
	public void disposeSendVerify() {
		send_verify.setClickable(false);
		SENDVERIFYFLAG = false;
		sendVerifition();

		verfition_visibility.setVisibility(View.GONE);
		count_down.setVisibility(View.VISIBLE);
		count_tv.setVisibility(View.VISIBLE);

		time = 60;
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}

		timer = new Timer();
		mTimerTask = new TimerTask() {

			@Override
			public void run() {
				handler.sendEmptyMessage(1);
			}
		};
		timer.schedule(mTimerTask, 0, 1000);
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			if (time != 0) {
				count_down.setText(time + "");
				time--;
			} else if (time == 0) {
				verfition_visibility.setVisibility(View.VISIBLE);
				count_down.setVisibility(View.GONE);
				count_tv.setVisibility(View.GONE);
				send_verify.setClickable(true);

				if (mTimerTask != null) {
					mTimerTask.cancel();
					mTimerTask = null;
				}
				SENDVERIFYFLAG = true;
			}

		}

	};

	/**
	 * 
	 * 请求银行卡列表接口
	 */
	public void requestBankList() {
		String customerIdAndtoken = PreferenceUtils.getInstance()
				.getcustomerId(this);
		String[] ct = customerIdAndtoken.split("&");
		if (ct == null || ct.length < 2)
			return;

		KkdHttpMagager.getInstance().getMyBankManager(
				new TypeToken<List<BankMessage>>() {
				}.getType(), new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mList = (List<BankMessage>) responseBody;
						cardname_tv.setText(mList.get(0).getBankName());

						cardno_tv.setText(mList.get(0).getCardNo());
						if (bankStatusas != null) {
							if (bankStatusas[0].equals("1")) {
								tip_bankname.setText(mList.get(0).getBankName()
										+ "充值限额");
							} else if (bankStatusas[0].equals("0")) {
								tip_bankname.setText(mList.get(0).getBankName()
										+ "充值方式变更");
							}
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(desc);
					}
				});

		// KkdHttpMagager.getInstance().getMyBankManager(ct[1],
		// customerIdAndtoken, ct[0], MyBank.class, new HttpCallBackT() {
		//
		// @Override
		// public void onSuccess(int statusCode, Object res) {
		// MyBank myBank = (MyBank) res;
		// if (myBank.getCode() == 0) {
		// mList = myBank.getData();
		// cardname_tv.setText(mList.get(0).getBankName());
		// cardno_tv.setText(mList.get(0).getCardNo());
		// } else {
		// Toasttool.MyToast(RechargeActivity.this,
		// myBank.getdesc());
		// }
		// }
		//
		// @Override
		// public void onFailure(int statusCode, byte[] responseBody,
		// Throwable error) {
		// }
		// });
	}

	/**
	 * 请求充值接口
	 */
	public void nextRechrge() {

		KkdHttpMagager.getInstance().getRechargeManager(ticket, orderId,
				recharge_verify_ed.getText().toString(), String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {

						try {
							JSONObject jsonObject = new JSONObject(responseBody
									.toString());
							JSONObject jsonObject_depositTips = jsonObject
									.optJSONObject("depositTips");
							String couTopDesc = jsonObject_depositTips
									.optString("couTopDesc");
							String couAmount = jsonObject_depositTips
									.optString("couAmount");
							String couponCount = jsonObject_depositTips
									.optString("couponCount");
							if (!TextUtils.isEmpty(couAmount)
									&& !TextUtils.isEmpty(couTopDesc)) { // 说明有新手红包
								if (dialog_newtask != null) {
									dialog_newtask.cancel();
									dialog_newtask = null;
								}
								dialog_newtask = DialogUtils
										.finishFirstRechargeDialog(
												RechargeActivity.this,
												couTopDesc, couAmount,
												couponCount,
												new OnSingleClickListener() {

													@Override
													public void onSingleClick(
															View v) {
														if (dialog_newtask != null) {
															dialog_newtask
																	.cancel();
														}
														Intent intent = new Intent(
																RechargeActivity.this,
																HomeActivity.class);
														startActivity(intent);
														HomeActivity.mActivity
																.homeNavigation();
														finish();
														PreferenceUtils
																.getInstance()
																.setMyproperty(
																		RechargeActivity.this,
																		"");
													}
												});
								dialog_newtask.show();
								progressbar
										.setImageResource(R.drawable.recharge_suc);
								details.setText(R.string.recharge_ok);
								close.setClickable(true);
							} else {
								showToast(R.string.recharge_ok);
								progressbar
										.setImageResource(R.drawable.recharge_suc);
								details.setText(R.string.recharge_ok);
								close.setClickable(true);
								handler.postDelayed(new Runnable() {

									@Override
									public void run() {
										finish();
										PreferenceUtils.getInstance()
												.setMyproperty(
														RechargeActivity.this,
														"");
									}
								}, 1000);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						RechargeActivity.this.code = statusCode;
						Message msg = new Message();
						msg.what = RECHARGE_FAIL;
						msg.obj = desc;
						close.setClickable(true);
						mHandler.sendMessage(msg);

					}
				});
	}

	/***
	 * 
	 * 重新获取验证码倒计时还原
	 * 
	 */
	public void errorTimerCancel() {
		if (!TextUtils.isEmpty(rechargeMax)) {
			ticket = "";
			orderId = "";
			recharge_verify_ed.setText("");
			recharge_bt.setEnabled(false);
			verfition_visibility.setVisibility(View.VISIBLE);
			count_down.setVisibility(View.GONE);
			count_tv.setVisibility(View.GONE);

			if (mTimerTask != null) {
				mTimerTask.cancel();
				mTimerTask = null;
			}
			SENDVERIFYFLAG = true;
		}

	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {

		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "加载中...");

		KkdHttpMagager.getInstance().getAccountInfoManager(
				AccountInfoRes.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						mAccountInfo = (AccountInfoRes) responseBody;
						wapDepositUrl = mAccountInfo.getWapDepositUrl();
						DecimalFormat df = new DecimalFormat("0.00");
						mobileTransferUrl=mAccountInfo.getMobileTransferUrl();
						alipayTransferUrl=mAccountInfo.getAlipayTransferUrl();
						otherTransferUrl=mAccountInfo.getOtherTransferUrl();
						balance = mAccountInfo.getBalance();

						balances = df.format(balance);

						card = mAccountInfo.getCard();// data.getJSONObject("card");

						String limit = card.getLimit();
						if (!limit.endsWith("null")) {
							String[] rechargeAndwithdarw = limit.split("@");

							String withdarw = rechargeAndwithdarw[0];

							String[] everymax = withdarw.split("/");
							rechargeMax = everymax[0];
							limitinfo = card.getLimitInfo2();// ("limitInfo2");
						} else {
							rechargeMax = "";
							limitinfo = "根据新浪方面的协议,该卡暂时只能用于提现";
						}

						newMisTips = mAccountInfo.getNewMisTips()
								.getNewMisTips();
						maxTime = (int) (mAccountInfo.getNewMisTips()
								.getTimeSpace() / 1000);
						if (!TextUtils.isEmpty(newMisTips)) {
							DepositTipsData jsonObject_depositTips = mAccountInfo
									.getDepositTips();
							depositTips1 = jsonObject_depositTips
									.getDepositTips1();
							depositTips2 = jsonObject_depositTips
									.getDepositTips2();
							depositTips3 = jsonObject_depositTips
									.getDepositTips3();
						}
						mHandler.sendEmptyMessage(ACCOUNTINFO_CODE_ZERO);
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						Message msg = new Message();
						msg.what = ACCOUNTINFO_CODE_ELSE;
						msg.obj = statusCode;
						mHandler.sendMessage(msg);
					}
				});
	}

	public void showDialog(String message) {
		// Ale

		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.subscribeDialog(this, message,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						mDialog.dismiss();
					}
				});
		mDialog.show();
	}

	/**
	 * 创建快捷充值，并发送验证码
	 */
	public void sendVerifition() {
		str = centre_ed.getText().toString();
		if (!TextUtils.isEmpty(str)
				&& str.substring(str.length() - 1).equals(".")) {
			str = str.substring(0, str.length() - 1);
		}

		KkdHttpMagager.getInstance().getRechargeSendVerifitionManager(str,
				String.class, new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {

						try {
							String responseString = responseBody.toString();
							JSONObject data = new JSONObject(responseString);
							ticket = data.getString("ticket");
							orderId = data.getString("orderId");
							amount = data.getString("amount");
							// showToast("短信已发送到您的手机上");
						} catch (JSONException e) {

							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						showToast(desc);
						resumeVerify();
						errorTimerCancel();
					}
				});
	}

	// /**
	// *
	// * 读取短信验证码
	// */
	// public void getSMSVerificationCode() {
	// filter2 = new IntentFilter();
	// filter2.addAction("android.provider.Telephony.SMS_RECEIVED");
	// filter2.setPriority(Integer.MAX_VALUE);
	// smsReceiver = new BroadcastReceiver() {
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// Object[] objs = (Object[]) intent.getExtras().get("pdus");
	// for (Object obj : objs) {
	// byte[] pdu = (byte[]) obj;
	// SmsMessage sms = SmsMessage.createFromPdu(pdu);
	// // 短信的内容
	// String message = sms.getMessageBody();
	// LogUtil.d("logo", "message     " + message);
	// // 短息的手机号。。+86开头？
	// String from = sms.getOriginatingAddress();
	// LogUtil.d("logo", "from     " + from);
	//
	// if (!TextUtils.isEmpty(from)) {
	// if (message.indexOf("快快贷") != -1
	// || message.indexOf("新浪") != -1) {
	// String code = patternCode(message);
	// if (!TextUtils.isEmpty(code)) {
	// strContent = code;
	// mHandler.sendEmptyMessage(RED_NOTE);
	// }
	// }
	// }
	// }
	// }
	// };
	// registerReceiver(smsReceiver, filter2);
	// }

	/**
	 * 匹配短信中间的4,6个数字（验证码等）
	 * 
	 * @param patternContent
	 * @return
	 */
	private String patternCode(String patternContent) {
		if (TextUtils.isEmpty(patternContent)) {
			return null;
		}
		Pattern p = Pattern.compile(patternCoder);
		Matcher matcher = p.matcher(patternContent);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// unregisterReceiver(smsReceiver);
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
			mTimerTask = null;
		}
		if (onlineBankingDialog != null) {
			onlineBankingDialog.cancel();
			onlineBankingDialog = null;
		}
		if (dialog_newtask != null) {
			dialog_newtask.cancel();
			dialog_newtask = null;
		}
		if (mTimerTask_newTask != null) {
			mTimerTask_newTask.cancel();
			mTimerTask_newTask = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		if (mSinaDialog != null) {
			mSinaDialog.cancel();
			mSinaDialog = null;
		}
	}

	@Override
	public void onBackPressed() {

		if (pop_line.getVisibility() == View.VISIBLE) {
			closePopwin();
		} else {
			super.onBackPressed();
		}

	}

	/****************
	 * 网银支付Dialog
	 ****************/
	Dialog onlineBankingDialog;

	public void onlineBankingDialog(String amount, String wapDepositUrl) {
		if (onlineBankingDialog != null) {
			onlineBankingDialog.cancel();
			onlineBankingDialog = null;
		}
		onlineBankingDialog = DialogUtils.onlineBankingDialog(this,
				wapDepositUrl, amount, new OnClickListener() {

					@Override
					public void onClick(View v) {
						onlineBankingDialog.dismiss();
						finish();
					}
				});
		onlineBankingDialog.show();
	}

	public void hideKeyBoard(Activity aty) {
		try {
			// ((InputMethodManager)
			// getSystemService(Context.INPUT_METHOD_SERVICE))
			// .hideSoftInputFromWindow(centre_ed.getWindowToken(),
			// InputMethodManager.HIDE_NOT_ALWAYS);
			((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(
							recharge_verify_ed.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);

		} catch (Exception e) {
			// 忽略掉，因为出异常基本等于是键盘未打开的情况
		}

	}

	public int maxTime = 0;
	private int mRecordTime = 0;
	private boolean isRecoding = false;
	public static final int RECORD_TIMER = 8112;
	public static final int RECORD_DONE = 8113;
	public static final int RECORD_ERROR = 8114;
	public static final int PERIOD = 1000;
	private TimerTask mTimerTask_newTask = null;
	private Timer mTimer = new Timer();
	public TimerHandler mTimerHandler = new TimerHandler(this);

	public void updateNewTaskSpaceTime() {
		int dtime = maxTime - mRecordTime;
		int ss = dtime % 60;
		int mm = (dtime / 60) % 60;
		int hh = dtime / 60 / 60;
		String tip_time_newtask = "";
		if (hh < 1) { // 不足一小时
			tip_time_newtask = "新手任务将在" + mm + "分" + ss + "秒后结束";
		} else if (hh >= 1 && hh < 24) { // 小于一天大于1小时
			tip_time_newtask = "新手任务将在今天24时结束";
		} else if (hh >= 24) { // 大于一天
			tip_time_newtask = "新手任务将在" + hh / 24 + "天后结束";
		}
		tv_time_newTask.setText(tip_time_newtask);
	}

	public void onTimerFinish() {
		if (mTimerTask_newTask != null) {
			mTimerTask_newTask.cancel();
			mTimerTask_newTask = null;
		}
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
		getAccountInfo();
	}

	public void startTime() {
		mRecordTime = 0;
		if (!isRecoding) {
			if (mTimerTask_newTask != null) {
				mTimerTask_newTask.cancel();
				mTimerTask_newTask = null;
			}
			if (mTimer != null) {
				mTimer.cancel();
				mTimer = null;
			}
			mTimerTask_newTask = new RecordTimeTask();
			mTimer = new Timer();
			mTimer.schedule(mTimerTask_newTask, 0, PERIOD);
		}

		isRecoding = true;

	}

	private class RecordTimeTask extends TimerTask {
		@Override
		public void run() {
			if (isRecoding) {
				mRecordTime++;
				if (mRecordTime <= maxTime) {
					Message message = new Message();
					message.what = RECORD_TIMER;
					message.obj = mRecordTime;
					mTimerHandler.sendMessage(message);
				} else {
					Message message = new Message();
					message.what = RECORD_DONE;
					message.arg1 = mRecordTime;
					message.obj = "";
					mTimerHandler.sendMessage(message);
					isRecoding = false;
				}
			}

		}
	}

	public static class TimerHandler extends Handler {
		WeakReference<RechargeActivity> reference;

		public TimerHandler(RechargeActivity activity) {
			reference = new WeakReference<RechargeActivity>(activity);
		}

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case RECORD_TIMER:
				if (reference != null && reference.get() != null)
					reference.get().updateNewTaskSpaceTime();
				break;
			case RECORD_DONE:
				if (reference != null && reference.get() != null)
					reference.get().onTimerFinish();
				break;
			default:
				break;
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == KKDSinaWebActivity.SET_PWD) {
			if (resultCode == KKDSinaWebActivity.SET_PWD_SUCCESS) {// 新浪页面充值成功的回调
				finish();
			} else {
				showSinaDialog();
			}
		}
	}
}
